<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" placeholder="部门名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryDept">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportExcel">导出数据</el-button>
        </el-form-item>
        <el-form-item>
          <!-- 默认name="file" -->
          <!-- post -->
          <el-upload class="upload-demo"
                     action="http://localhost:8080/shop/importExcel"
                     list-type="text">
            <el-button type="warning">点击导入</el-button>
          </el-upload>
        </el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <el-table :data="depts" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" label="序号" width="60">
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="100">
      </el-table-column>
      <el-table-column prop="tel" label="座机" width="130">
      </el-table-column>
      <el-table-column prop="logo" label="图标" min-width="50" sortable>
        <template scope="scope">
          <img :src="imgPrefix+scope.row.logo" width="50px">
        </template>
      </el-table-column>
      <el-table-column prop="registerTime" label="注册时间" width="180">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80" sortable>
        <template scope="scope">
          <span v-if="scope.row.state==1" style="color: hotpink">待审核</span>
          <span v-if="scope.row.state==2" style="color: blue">待激活</span>
          <span v-if="scope.row.state==3" style="color: green">正常使用</span>
          <span v-if="scope.row.state==4" style="color: red">驳回</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template scope="scope">
          <el-button size="small" type="info" disabled @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="small" type="danger" disabled @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="warning" :disabled="scope.row.state!==1" size="small" @click="handleAudit(scope.$index, scope.row)">店铺审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="size" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
      <el-dialog :title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
<!--		<el-dialog title="编辑" v-model="addFormVisible" :close-on-click-modal="false">-->
			<el-form :model="addForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="addForm.sn" auto-complete="off"></el-input>
				</el-form-item>

        <el-form-item label="部门名称" prop="sn">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="是否启用" prop="sn">
          <el-switch
              v-model="addForm.state"
              active-color="#13ce66"
              inactive-color="#ff4949">
          </el-switch>
        </el-form-item>

        <el-form-item label="部门经理" prop="sn">
          <el-select v-model="addForm.managerId" clearable placeholder="请选择">
            <el-option
                v-for="item in emps"
                :key="item.id"
                :label="item.username"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!--
          :options="options" - 数据 - 无限极树- 集合
                  label:'name' - 回显哪一个属性值
                  value:'id' - 传值，将id传递给v-model="saveForm.parent_id"
          回显机制：
          1. 先根据【v-model="saveForm.parent_id"】parent_id与deptTree中的每一个对象进行比对
          2. 比对到之后回显对象的哪一个属性【label: 'name'】对象的name属性值
          传值机制：
          1. 当选择一个上级部门之后将部门的id【value: 'id'】
          2. 传值给【v-model="saveForm.parent_id"】parent_id，最后更新到数据库
        -->
        <el-form-item label="上级部门" prop="sn" >
          <el-cascader
              v-model="addForm.parentId"
              :options="options"
              :props="{ checkStrictly: true ,
                        label: 'name', // 级联框显示那个属性的值
                        value: 'id'     // 回显时需要,回传值的时候也需要
                      }"
              clearable></el-cascader>
        </el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
    <!-- 审核模态框 -->
    <el-dialog title="审核店铺" :visible.sync="shopAuditVisible" :close-on-click-modal="false">
      <el-form :model="shopAuditLog" label-width="80px"  ref="shopAuditLogForm">
        <el-form-item label="备注" prop="note">
          <el-input type="textarea" v-model="shopAuditLog.note"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="shopAuditVisible = false">取消</el-button>
        <el-button type="primary" @click.native="auditPass">通过</el-button>
        <el-button type="primary" @click.native="auditReject">驳回</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
	import {id} from "html-webpack-plugin/lib/chunksorter";

  export default {
		data() {
			return {
				filters: {
					name: ''
				},
        imgPrefix:"http://115.159.88.63:8800",
				depts: [],
				emps: [],
        options: [],
				total: 0,
        size: 5,
				page: 1,
        title: "新增",
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
					id: 0,
					name: '',
					sex: -1,
					age: 0,
					birth: '',
					addr: ''
				},

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据
				addForm: {
					name: '',
					sn: '',
          state: true,
          managerId:'',
          parentId:''
				},
        //审核模态框
        shopAuditVisible: false,
        //编辑界面数据
        shopAuditLog: {
          shopId: null,
          note:''
        }

			}
		},
		methods: {
      //点击店铺审核弹出模态框
      handleAudit: function (index, row) {
        this.shopAuditLog.shopId = row.id;
        this.shopAuditVisible = true;
      },
//审核驳回
      auditReject(){
        this.$http.post("/shop/audit/reject",this.shopAuditLog).then(res=>{
          if(res.data.success){
            this.$message({
              message: '驳回成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: '驳回失败',
              type: 'error'
            });
          }
          this.shopAuditVisible = false;
          this.getShops();
        })
      },
      //审核通过
      auditPass(){
        this.$http.post("/shop/pass",this.shopAuditLog).then(result=>{
          result = result.data;
          if(result.success){
            this.$message({
              message: '审核通过',
              type: 'success'
            });
          }else{
            this.$message({
              message: '审核失败',
              type: 'error'
            });
          }
          this.shopAuditVisible = false;
          this.getShops();
        })
      },
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getShop();
			},
      queryDept(){
        this.page = 1
        this.getShop()
      }
      ,

			getShop() {
				let para = {
          currentPage: this.page,
          pageSize: this.size,
          keyword: this.filters.name
				};
				this.listLoading = true;
        //发送请求获取部门信息
        this.$http.post("/shop/pageList",para).then(res=>{
            console.log(res)
          if(res.data.success){
            this.listLoading = false;
            this.depts = res.data.resultObj.data
            this.total = res.data.resultObj.count
          }
        })

				// //NProgress.start();
				// getUserListPage(para).then((res) => {
				// 	this.total = res.data.total;
				// 	this.depts = res.data.depts;
				// 	this.listLoading = false;
				// 	//NProgress.done();
				// });
			},
      //获取用户列表
      getEmps(){
        this.$http.get("/emp/all").then(res=>{
          console.log(res.data.resultObj)
          this.emps = res.data.resultObj;
        });
      },
      getShopTree(){
        this.$http.get("/dept/getShopTree").then(res=>{
          console.log(res.data.resultObj)
          this.options = res.data.resultObj;
        });
      },
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
					removeUser(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getShop();
					});
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (row) {
				this.addFormVisible = true;
        this.title="修改"
        //回显赋值
				this.addForm = Object.assign({}, row);
        //分割dirpath
        var ids = this.addForm.dirPath.split("/")
        ids = ids.slice(1,ids.length-1);//去掉头尾
        //将字符串转为数字
        for (let i = 0; i < ids.length; i++) {
          ids[i] = Number(ids[i])
        }
        this.addForm.parentId = ids
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.addForm = {
          name: '',
          sn: '',
          state: true,
          managerId:'',
          parentId:''
				};
			},
      exportExcel:function (){
        location.href="http://localhost:8080/shop/export";
      },
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.addForm);
              para.state=para.state?1:0

              //前端无限级树的处理，有五种情况：null,[],[2],[2,5],2 - 后端用Long接收的不能是数组
              let temp = para.parentId;
              if(temp == null || temp.length==0){
                para.parentId = null;
              } else if(temp.length){//有值，没有报错，数组 [2][2,5]
                para.parentId = temp[temp.length-1];//直接获取最后一个
              }


              this.$http.put("/dept/save",para).then(res=>{
                if(res.data.success){
                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  });
                  this.$refs['editForm'].resetFields();//重置校验规则
                  this.addFormVisible = false;//关闭对话框
                  this.getShop();//重新刷新列表
                }else {
                  this.$message.error(res.data.message);
                }
                this.editLoading = false;//关闭忙等
              })
						});
					}
				});
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.addForm);
							para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							addUser(para).then((res) => {
								this.addLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getShop();
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { ids: ids };
					batchRemoveUser(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getShop();
					});
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getShop();
		}
	}

</script>

<style scoped>

</style>